#!/usr/bin/env perl

use strict;
use warnings;

my @size = split "\t", <>;

shift @size;

my %x;
my %ord;

print <<END
#mega
!Title Test;
!Format DataType=distance;

END
;

while ( <> ) {
  chomp;
  my ( $id, @x ) = split "\t";
  $id =~ s/\"//g;
#  $label = join(":", (split "/", $label)[-2,-1]) unless $label eq "length";
  $x{$id} = [@x];
  $ord{$id} = $.;
  my $short_id = (split "/", $id)[-1];
  print "#" . "$short_id\n";
}

print "\n";

foreach my $i ( sort {$ord{$a} <=> $ord{$b}} keys %x ) {
  foreach my $j ( sort {$ord{$a} <=> $ord{$b}} keys %x ) {
    last if $ord{$j} >= $ord{$i};
    my $N = 0;
    my $Q = 0;
    foreach my $k ( 0 .. scalar @{$x{$i}} - 1 ) {
      $N += abs($x{$i}->[$k] - $x{$j}->[$k]);
      $Q += $x{$i}->[$k] + $x{$j}->[$k];
    }
    my $dist = sprintf("%6.4g", $N/$Q);
    print " $dist";
  }
  print "\n";
}
